const assert = require('assert');
const path = require('path');

const WxWorkApi = require('./apis');

const wxWorkApi = new WxWorkApi();

function wxWorkLogin({ asyncGetTokenFn, checkStateFn }) {
    assert(
        asyncGetTokenFn && typeof asyncGetTokenFn === 'function',
        '错误的token获取方法'
    );

    const getAccessToken = asyncGetTokenFn;
    const checkState =
        checkStateFn && typeof checkStateFn === 'function'
            ? checkStateFn
            : () => {
                  return true;
              };

    return (req, res, next) => {
        (async () => {
            try {
                let { code, state } = req.query;
                if (!code) return res.status(403).send('未经授权的访问');
                let isStatePassed = await checkState(state, req);
                if (!isStatePassed) return res.status(403).send('错误的授权参数');
                let accessToken = await getAccessToken();
                let userId = await wxWorkApi.getUserIdForLogin(
                    accessToken,
                    code
                );
                let member = await wxWorkApi.getMember(accessToken, userId);
                req.qymember = member;
                return next();
            } catch (ex) {
                console.error(ex);
                res.status(400).send(ex.message);
            }
        })();
    };
}

module.exports = wxWorkLogin
